
//
//  QCRefreshControl.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/2/7.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit
//设置控件的高度
private let QCRefreshControlH: CGFloat = 50
//自定义下拉刷新控件的状态
enum QCRefreshControlType :String {
    case normal = "正常中"
    case pulling = "下拉中"
    case refreshing = "刷新中"
}
class QCRefreshControl: UIControl {
   
    var scrollView: UIScrollView?
    
    //实时记录刷新控件的状态
    var refreshType:QCRefreshControlType = .normal{
        didSet{
           
            //设置messageLabel的文字
            messageLabel.text = refreshType.rawValue
            switch refreshType {
            case .normal:
                //设置箭头动画
            UIView.animate(withDuration: 0.25, animations: { 
                //恢复原状
                self.pullRefreshImageView.transform = CGAffineTransform.identity
            })
             
            //判断 上一个状态是否是刷新中
            if oldValue == .refreshing {
                
                UIView.animate(withDuration: 0.25, animations: {
                    self.scrollView!.contentInset.top = self.scrollView!.contentInset.top - QCRefreshControlH
                }, completion: { (_) in
                    //显示箭头 停止风火轮
                    self.indicatorView.stopAnimating()
                    self.pullRefreshImageView.isHidden = false
                })

            }
                
            case .pulling:
               //设置箭头动画
                UIView.animate(withDuration: 0.25, animations: {
                  self.pullRefreshImageView.transform = CGAffineTransform(rotationAngle: CGFloat(-3*M_PI))
                })
                
            case .refreshing:
                
                UIView.animate(withDuration: 0.25, animations: {
                   
                    self.scrollView!.contentInset.top = self.scrollView!.contentInset.top + QCRefreshControlH
                    //隐藏箭头 和 风火轮开始动画
                    self.pullRefreshImageView.isHidden = true
                    self.indicatorView.startAnimating()
                    
                }, completion: { (_) in
                    //告知外界刷新数据
                    self.sendActions(for: UIControlEvents.valueChanged)
                })
                
            }
        }
    }
    
    
   override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -QCRefreshControlH, width: UIScreen.main.bounds.width, height: QCRefreshControlH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //给外界提供一个调用的方法 ->停止刷新
    func endRefreshing() {
        //把控件的状态改为正常
        refreshType = .normal
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        //判断newSuperview 是否为nil 是否可以滚动
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        
        self.scrollView = scrollView
        
        //KVO 观察 contentoffset 属性变化
        //注册
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
        
    }
    
    //实现
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //计算判断的临界值
        let maxY  = self.scrollView!.contentInset.top + QCRefreshControlH
        //计算拖拽的偏移量
        let contentOffsetY = self.scrollView!.contentOffset.y
        
        //判断状态是否是拖动状态
        if self.scrollView!.isDragging {
            
            if contentOffsetY >= -maxY && refreshType == .pulling {
                refreshType = .pulling
                
            } else if contentOffsetY < -maxY && refreshType == .normal {
                
                refreshType = .pulling
            }
            
        }else {
            
            //当在下拉状态时 ->刷新
            if refreshType == .pulling {
                
                refreshType = .refreshing
            }
            
        }
        
        
    }
    
    private func setupUI(){
        backgroundColor = UIColor.orange
        
        addSubview(messageLabel)
        addSubview(pullRefreshImageView)
        addSubview(indicatorView)
        
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        //约束
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        pullRefreshImageView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: pullRefreshImageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: pullRefreshImageView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
    }
    
    private lazy var messageLabel: UILabel = {
       let lab = UILabel()
       lab.font = UIFont.systemFont(ofSize: 14)
       lab.textAlignment = .center
       lab.textColor = UIColor.white
       lab.text = "正常中"
       return lab
    }()
    
    //箭头
    private lazy var pullRefreshImageView: UIImageView = UIImageView(image: UIImage(named:"tableview_pull_refresh"))
    //风火轮
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    
}
